import { asyncRoutes, constantRoutes } from "@/router";

/**
 * 判断是否具有当前路由访问权限
 * 匹配的是路由的name属性
 * 替换路由中的no-cache和title属性
 * @param menus roles permission
 * @param route current route
 */
function hasPermission(menus, route) {
    if (!route.name) return false;
    const index = menus.findIndex((menu) => menu.name == route.name);

    if (index !== -1) {
        const menu = menus[index];
        // url
        route.path = menu.url;
        if (!route.meta) {
            route.meta = {};
        }
        // 路由元信息
        route.meta.title = menu.title;
        route.meta.noCache = menu.noCache || true;
        route.meta.icon = menu.icon;
    }
    return index !== -1;
    // return true;
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param menus
 */
export function filterAsyncRoutes(routes, menus) {
    const res = [];

    routes.forEach((route) => {
        const tmp = { ...route };
        if (hasPermission(menus, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, menus);
            }
            res.push(tmp);
        }
    });

    return res;
}

const state = {
    routes: [],
    addRoutes: [],
};

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes;
        state.routes = constantRoutes.concat(routes);
    },
};

const actions = {
    generateRoutes({ commit }, menus) {
        return new Promise((resolve) => {
            // 遍历路由表，动态添加路由
            let accessedRoutes = filterAsyncRoutes(asyncRoutes, menus);
            accessedRoutes.push({ path: "*", redirect: "/404", hidden: true });
            commit("SET_ROUTES", accessedRoutes);
            resolve(accessedRoutes);
        });
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};
